﻿
//

//


using EMSNet.Core.Service;
using Microsoft.AspNetCore.Http;

namespace EMSNet.Service;

/// <summary>
/// 基础配置服务 🧩
/// </summary>
[ApiDescriptionSettings(ServiceConst.GroupName, Order = 100)]
public class EmsBaseconfigService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<EmsBaseconfig> _emsBaseconfigRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public EmsBaseconfigService(SqlSugarRepository<EmsBaseconfig> emsBaseconfigRep, ISqlSugarClient sqlSugarClient)
    {
        _emsBaseconfigRep = emsBaseconfigRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询基础配置 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询基础配置")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<EmsBaseconfigOutput>> Page(PageEmsBaseconfigInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _emsBaseconfigRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.name.Contains(input.Keyword) || u.DataValueFormat.Contains(input.Keyword) || u.ToleranceFormat.Contains(input.Keyword) || u.DataValueMeter.Contains(input.Keyword) || u.ToleranceMater.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.name), u => u.name.Contains(input.name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.DataValueFormat), u => u.DataValueFormat.Contains(input.DataValueFormat.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ToleranceFormat), u => u.ToleranceFormat.Contains(input.ToleranceFormat.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.DataValueMeter), u => u.DataValueMeter.Contains(input.DataValueMeter.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ToleranceMater), u => u.ToleranceMater.Contains(input.ToleranceMater.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Category), u => u.Category == input.Category)
            .LeftJoin<EmsDictionary>((u, category) => u.Category == category.code)
            .Select((u, category) => new EmsBaseconfigOutput
            {
                Id = u.Id,
                TenantId = u.TenantId,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                IsDelete = u.IsDelete,
                Category = u.Category,
                CategoryFkDisplayName = $"{category.name}",
                name = u.name,
                DataValueFormat = u.DataValueFormat,
                ToleranceFormat = u.ToleranceFormat,
                DataValueMeter = u.DataValueMeter,
                ToleranceMater = u.ToleranceMater,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取基础配置详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取基础配置详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<EmsBaseconfig> Detail([FromQuery] QueryByIdEmsBaseconfigInput input)
    {
        return await _emsBaseconfigRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加基础配置 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加基础配置")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddEmsBaseconfigInput input)
    {
        var entity = input.Adapt<EmsBaseconfig>();
        return await _emsBaseconfigRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新基础配置 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新基础配置")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateEmsBaseconfigInput input)
    {
        var entity = input.Adapt<EmsBaseconfig>();
        await _emsBaseconfigRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除基础配置 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除基础配置")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteEmsBaseconfigInput input)
    {
        var entity = await _emsBaseconfigRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _emsBaseconfigRep.FakeDeleteAsync(entity);   //假删除
        //await _emsBaseconfigRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除基础配置 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除基础配置")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteEmsBaseconfigInput> input)
    {
        var exp = Expressionable.Create<EmsBaseconfig>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _emsBaseconfigRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _emsBaseconfigRep.FakeDeleteAsync(list);   //假删除
        //return await _emsBaseconfigRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataEmsBaseconfigInput input)
    {
        var categoryData = await _emsBaseconfigRep.Context.Queryable<EmsDictionary>()
            .InnerJoinIF<EmsBaseconfig>(input.FromPage, (u, r) => u.code == r.Category)
            .Select(u => new {
                Value = u.code,
                Label = $"{u.name}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "category", categoryData },
        };
    }
    
    /// <summary>
    /// 导出基础配置记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出基础配置记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageEmsBaseconfigInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportEmsBaseconfigOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "基础配置导出记录");
    }
    
    /// <summary>
    /// 下载基础配置数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载基础配置数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportEmsBaseconfigOutput>(), "基础配置导入模板", (_, info) =>
        {
            if (nameof(ExportEmsBaseconfigOutput.CategoryFkDisplayName) == info.Name) return _emsBaseconfigRep.Context.Queryable<EmsDictionary>().Select(u => $"{u.name}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入基础配置记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入基础配置记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportEmsBaseconfigInput, EmsBaseconfig>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 类型
                    var categoryLabelList = pageItems.Where(x => x.CategoryFkDisplayName != null).Select(x => x.CategoryFkDisplayName).Distinct().ToList();
                    if (categoryLabelList.Any()) {
                        var categoryLinkMap = _emsBaseconfigRep.Context.Queryable<EmsDictionary>().Where(u => categoryLabelList.Contains($"{u.name}")).ToList().ToDictionary(u => $"{u.name}", u => u.code);
                        //pageItems.ForEach(e => {
                        //    e.Category = categoryLinkMap.GetValueOrDefault(e.CategoryFkDisplayName ?? "");
                        //    if (e.Category == null) e.Error = "类型链接失败";
                        //});
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<EmsBaseconfig>>();
                    
                    var storageable = _emsBaseconfigRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.name?.Length > 100, "名称长度不能超过100个字符")
                        .SplitError(it => it.Item.DataValueFormat?.Length > 100, "数值格式长度不能超过100个字符")
                        .SplitError(it => it.Item.ToleranceFormat?.Length > 100, "折标系数格式长度不能超过100个字符")
                        .SplitError(it => it.Item.DataValueMeter?.Length > 100, "数值单位长度不能超过100个字符")
                        .SplitError(it => it.Item.ToleranceMater?.Length > 100, "折合系数单位长度不能超过100个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
